<template>
  <div>
    <van-sticky>
      <MyHeader :title="shop.name" :arrow="true"/>
      <van-row class="shop-info">
        <van-col :span="8">
          <van-image :src="baseImgPath+shop.image_path" height="70" width="70" round></van-image>
        </van-col>
        <van-col :span="15">
          <div><span>口号:</span>{{ shop.promotion_info }}</div>
          <div>
            <span>承诺：</span>
            <van-tag style="margin: 5px" plain type="success" v-for="item in shop.supports" :key="item.id">
              {{ item.name }}
            </van-tag>
          </div>
          <div>
            <span>店铺类型：{{ shop.category.split("/")[0] }}</span>
          </div>
        </van-col>
      </van-row>
      <van-row class="shop-info">
        <van-col :span="18">
          <van-notice-bar left-icon="volume-o" :scrollable="false" background="#FFD101">
            <van-swipe :autoplay="3000" :show-indicators="false" :vertical="true"
                       style="height: 40px;line-height: 40px">
              <van-swipe-item v-for="item in shop.activities" :key="item.id">
                <van-row>
                  <van-col :span="24">{{ item.description }}</van-col>
                </van-row>
              </van-swipe-item>
            </van-swipe>
          </van-notice-bar>
        </van-col>
        <van-col :span="6">
          <div style="font-size: 14px;color: #ed6a0c">共{{ shop.activities.length }}个活动</div>
        </van-col>
      </van-row>
    </van-sticky>
    <van-tabs id="shopTab" v-model="tabIndex" animated sticky offset-top="160">
      <van-tab title="商品">
        <van-tree-select class="select-tree" :items="categoryList" :main-active-index.sync="treeActive">
          <template #content>
            <!--index的范围1-数组长度-->
            <template v-for="index in categoryList.length">
              <!-- template的for循环会得到和分类个数一致的div，但是我们每次只需要展示一个div即可，treeActive表示左边导航按钮选中的下标，和右边div的下标对应则展示，否则隐藏 -->
              <div :key="index" v-if="treeActive===index-1">
                <!--分类的标题-->
                <h3>{{ categoryList[index - 1].text }}</h3>
                <!--展示当前的分类中有哪些食物，但是后台接口返回的食物列表是整个店铺的所有食物组成的数组-->
                <div>
                  <!--遍历完整的食物数组-->
                  <template v-for="(food,fi) in cartList">
                    <!--当前食物所在div的下标就是分类的下标-->
                    <!--食物的分类ID和当前div所属的分类ID相等时，显示该食物-->
                    <van-card class="food" :key="fi" v-if="categoryList[index-1].id==food.category_id" num="2"
                              :desc="food.description" :title="food.name" :thumb="baseImgPath+food.image_path"
                    >
                      <template slot="price-top">
                        <div>
                          规格：
                          <!--每个食物的规格个数不同，因此也需要单独的for循环来遍历处理数据-->
                          <!--默认情况下，food.specActive的值一定是0，表示的是选中的食物规格是哪个，单击事件需要改变的也是这个属性的值-->
                          <!--@click="changeSpec(fi,specIndex)"中fi表示的是当前被点击的规格所属的食物的下标-->
                          <van-tag style="margin-right: 3px" plain v-for="(spec,specIndex) in food.specfoods"
                                   :key="specIndex" :type="specIndex===food.specActive?'success':'warning'"
                                   @click="changeSpec(fi,specIndex)">{{ spec.name }}
                          </van-tag>
                        </div>
                      </template>
                      <template slot="price">
                        <div>
                          <span>价格：</span>￥
                          <span
                            style="margin-right: 10px;font-weight: bold">{{
                              food.specfoods[food.specActive].price
                            }}</span>
                        </div>
                      </template>
                      <template slot="bottom">
                        <div>
                          <span>打包：</span>￥
                          <span>{{ food.specfoods[food.specActive].packing_fee }}</span>
                        </div>
                      </template>
                      <template #num>
                        <van-stepper style="margin-top: 10px;margin-right: 5px" v-model="food.selectCount" theme="round"
                                     button-size="15" input-width="15" min="0" :show-minus="food.showMinus"
                                     :show-input="food.showInput" disable-input :name="fi" @change="changeNum"/>
                      </template>
                    </van-card>
                  </template>
                </div>
              </div>
            </template>
          </template>
        </van-tree-select>
      </van-tab>
      <van-tab title="评价">这里是评价</van-tab>
      <van-tab title="信息">这里是信息</van-tab>
    </van-tabs>
    <van-goods-action>
      <van-goods-action-icon icon="cart-o" text="购物车" :badge="cartCount" @click="showCart=cartCount>0"/>
      <div>
        <div>总价￥<span>{{ carSumPrice }}</span></div>
        <div>配送费￥5</div>
      </div>
      <van-goods-action-button type="danger" :disabled="cartCount===null" @click="$router.push(`order/detail`)"
                               text="立即下单"/>
    </van-goods-action>
    <van-action-sheet style="max-height: 50vh" title="购物车详情" v-model="showCart">
      <div style="padding-bottom: 50px">
        <template v-for="(item,index) in cartList">
          <van-card style="padding:0 10px" v-if="item.selectCount>0" :key="index" :thumb="baseImgPath+item.image_path">
            <div slot="title"><b>{{ item.name }}</b></div>
            <div slot="desc">
              规格：
              <van-tag plain type="success">{{ item.specfoods[item.specActive].name }}</van-tag>
            </div>
            <div slot="price">价格：{{ item.specfoods[item.specActive].price }}</div>
            <div slot="bottom">包装：{{ item.specfoods[item.specActive].packing_fee }}</div>
            <div slot="num">
              <van-stepper theme="round" disable-input button-size="15" min="0" input-width="15" @change="changeCartNum"
                           v-model="item.selectCount" :name="index"></van-stepper>
            </div>
          </van-card>
        </template>
      </div>
      <van-submit-bar button-text="下单" @submit="$router.push(`order/detail`)" :price="orderSumPrice"></van-submit-bar>
    </van-action-sheet>
  </div>
</template>

<script>
import MyHeader from '@/components/MyHeader'

const shop = {
  name: '',
  image_path: '',
  promotion_info: '',
  supports: [],
  category: '',
  activities: []
}
export default {
  name: 'ShopDetail',
  components: {MyHeader},
  data() {
    return {
      shop: {...shop},
      baseImgPath: process.env.VUE_APP_BASE_API + '/file/getImgStream?fileName=',
      tabIndex: 0,
      showCart: false,
      categoryList: [],
      treeActive: 0,
      foodList: [],
      cartCount: 0,
      carSumPrice: 0
    }
  },
  computed: {
    orderSumPrice() {
      return (this.carSumPrice + 5) * 100
    },
    cartList() {
      const cartInfo = this.$store.state.cartInfo
      if (cartInfo.userId === this.$cookies.get('user_id') && cartInfo.shopId === this.getShopId()) {
        return cartInfo.cartList
      }
      return this.foodList
    }
  },
  methods: {
    getShop(shopId) {
      this.$axios.get(`/shopping/restaurant/${shopId}`).then(({data}) => {
        if (data.code === 20000) {
          this.shop.id = data.data.id
          this.shop.name = data.data.name
          this.shop.image_path = data.data.image_path
          this.shop.promotion_info = data.data.promotion_info
          this.shop.supports = data.data.supports
          this.shop.category = data.data.category
          // this.shop.activities = data.data.activities
          this.shop.activities = [{
            description: '满50-30,满100-70,会员免费',
            name: '满减优惠',
            id: 1
          }, {description: '充值500，到账600，再送200', name: '充值优惠', id: 2}]
          this.$store.commit('setShopInfo', this.shop)
        }
      })
    },
    getShopId() {
      return this.$route.query.id
    },
    getCategoryList() {
      this.$axios.get('/shopping/v2/menu', {params: {restaurant_id: this.getShopId()}})
        .then(({data}) => {
          if (data.code === 20000) {
            this.categoryList = data.data.map(item => {
              return {
                id: item.id,
                text: item.name
              }
            })
          }
        })
    },
    getFoodList() {
      this.$axios.get(`/shopping/v2/foodList/${this.getShopId()}`)
        .then(({data}) => {
          if (data.code === 20000) {
            this.foodList = data.data.map((item, index) => {
              return {
                ...item,
                specActive: 0,
                selectCount: 0,
                showMinus: false,
                showInput: false
              }
            })
            for (const food of this.foodList) {
              for (const cart of this.cartList) {
                if (food.item_id === cart.item_id) {
                  if (cart.selectCount > 0) {
                    food.selectCount = cart.selectCount
                    food.specActive = cart.specActive
                    food.showMinus = cart.showMinus
                    food.showInput = cart.showInput
                  }
                }
              }
            }
            // const cartInfo = {
            //   [this.$cookies.get('user_id')]: {
            //     [this.getShopId()]: {
            //       cartList: this.foodList
            //     }
            //   }
            // }
            this.$store.commit('setCartInfo', {
              userId: this.$cookies.get('user_id'),
              shopId: this.getShopId(),
              cartList: this.foodList
            })
          }
        })
    },
    changeSpec(foodIndex, specIndex) {
      this.cartList[foodIndex].specActive = specIndex
    },
    // 两种触发条件
    // 点击页面上的按钮会触发change
    // 其他方法导致count或selectCount发生变化也会触发change
    // 只要v-model绑定的那个属性的值变化，change就一定被触发
    changeNum(num, detail) {
      this.cartList[detail.name].showInput = num > 0
      this.cartList[detail.name].showMinus = num > 0
      this.getCartTotal()
    },
    changeCartNum() {
      this.getCartTotal()
      if (this.cartCount === null) {
        this.showCart = false
      }
    },
    getCartTotal() {
      /* 每次叠加购物车总数量时都要先清空之前的计数和 */
      this.cartCount = null
      this.carSumPrice = 0
      for (const food of this.cartList) {
        if (food.selectCount > 0) { /* 此处判断可以省略 */
          this.cartCount += food.selectCount
          this.carSumPrice += (food.specfoods[food.specActive].price + food.specfoods[food.specActive].packing_fee) * food.selectCount
        }
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.getShop(this.getShopId())
      this.getCategoryList()
      this.getFoodList()
      this.getCartTotal()
    })
  }
}
</script>

<style scoped lang="scss">
.shop-info {
  background-color: #FFD101;
  display: flex;
  align-items: center;
  justify-content: center;
}

.select-tree {
  height: calc(100vh - 260px) !important;
}

.food {
  padding: 0;

  .van-card__thumb {
    height: 60px;
    width: 60px;
  }
}
</style>
